package org.aom.litebean.module.security;

import java.util.Map;

import org.aom.entity.security.Resource;
import org.aom.litebean.module.base.BaseEntityFormBean;
import org.aom.service.security.IResourceManager;
import org.aom.util.FaceUtil;
import org.operamasks.faces.annotation.Action;
import org.operamasks.faces.annotation.BeforeRender;
import org.operamasks.faces.annotation.Bind;
import org.operamasks.faces.annotation.ManagedBean;
import org.operamasks.faces.annotation.ManagedBeanScope;
import org.operamasks.faces.annotation.ManagedProperty;
import org.operamasks.faces.annotation.Required;

@ManagedBean(name = "module.security.resourceFormBean", scope = ManagedBeanScope.REQUEST)
public class ResourceFormBean extends BaseEntityFormBean {

	@Bind(id = "resourceType", attribute = "value")
	@Required(message = "#{this.getMessages().get('required')}")
	private String resourceType;

	@Bind(id = "value", attribute = "value")
	@Required(message = "#{this.getMessages().get('required')}")
	private String value;

	@Bind(id = "name", attribute = "value")
	@Required(message = "#{this.getMessages().get('required')}")
	private String name;

	@Bind(id = "position", attribute = "value")
	@Required(message = "#{this.getMessages().get('required')}")
	private double position;

	private Resource resource;

	@ManagedProperty("#{resourceManager}")
	private IResourceManager resourceManager;

	@Override
	@Action(id="ok")
	protected void ok() {
		Map<String, Object> session = FaceUtil.getSessionMap();
		if(session.get(ACTION_NAME).toString().equals("add")){
			resource = new Resource();
		}else {
			selectedModuleId = (Long)session.get(SELECTED_MODULE_ID);
			resource = resourceManager.get(selectedModuleId);
		}
		resource.setName(name);
		resource.setPosition(position);
		resource.setResourceType(resourceType);
		resource.setValue(value);
		resourceManager.save(resource);
		cancel();
	}

	@Override
	protected void processCancel() {
		name = "";
		position = 0;
		value = "";
		resourceType = "";
	}

	@BeforeRender
	protected void beforeRender(boolean isPostBack) {
		initBaseResource();
		Map<String, Object> session = FaceUtil.getSessionMap();
		if (session.get(ACTION_NAME).toString().equals("mod")) {
			selectedModuleId = (Long) session.get(SELECTED_MODULE_ID);
			resource = resourceManager.get(selectedModuleId);
			name = resource.getName();
			position = resource.getPosition();
			value = resource.getValue();
			resourceType = resource.getResourceType();
		}
	}

}
